package com.mars.weixin.web.weixin.controller;

import java.io.File;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.mars.base.common.utils.http.HttpResult;
import com.mars.base.common.utils.web.ResponseResult;
import com.mars.base.web.BaseController;
import com.mars.component.mq.JmsQueueMessage;
import com.mars.weixin.common.WeixinContext;
import com.mars.weixin.enums.MediaType;
import com.mars.weixin.service.ApiService;

@RestController
@RequestMapping(value="/weixin/api")
public class WeixinApiController extends BaseController {
	private static Logger logger = LoggerFactory.getLogger(WeixinApiController.class);
	
	@Autowired
	private ApiService apiService ;
	
	@Autowired
	private JmsQueueMessage jmsQueueMessage ;
	
	/**
	 * 微信客户端上传文件到应用服务器
	 * @param mediaId 微信服务器上的素材mediaId或JSSDK的serverId
	 * @return
	 */
	@GetMapping(value="/upload/media/{mediaId}")
	public Object uploadMedia(@PathVariable String mediaId) {
		try {
			//1、从微信服务器上下载文件到本地
			HttpResult result = (HttpResult) this.apiService.downloadMedia(WeixinContext.getAccessToken(), mediaId, MediaType.image) ;
			
			if(result.getStatus()) {
				//获取本地文件的File对象
				File file = result.getFile() ;
				
				//2、发送异步消息（消费端操作：1、将本地文件上传到云存储服务器，2、将文件信息保存到数据库）
				this.jmsQueueMessage.send("weixin.media", file);
				
				return ResponseResult.ok() ;
			} else {
				String message = result.getMessage() ;
				
				logger.error("从微信服务器下载素材到本地失败：{}", message);
				return ResponseResult.build(false, message) ;
			}
		} catch (Exception e) {
			logger.error("文件下载失败：{}", e.getMessage());
			return ResponseResult.build(false, e.getMessage()) ;
		}
	}
	
}
